package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
public class blogController {
    @Autowired
    blogMapper blogMapper;
    @Autowired
    usersMapper usersMapper;
    @Autowired
    tagsMapper tagsMapper;
    @Autowired
    attentionMapper attentionMapper;
    @Autowired
    IntegralMapper integralMapper;


    //根据类型查询博客
    @GetMapping("/selectblogBytype/{type}")
    public String selectblogBytype(@PathVariable("type") String type) {
        List<blog> list = blogMapper.selectblogBytype(type);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setUsers(usersMapper.selectuser(list.get(i).getUser()));
        }
        return list.toString();
    }

    //根据id查询博主的信息
    @GetMapping("/selectblogByid/{id}")
    public String selectblogByid(@PathVariable("id") int id) throws ParseException {
        blog blog = blogMapper.selectblogByid(id);
        users users = usersMapper.selectuser(blog.getUser());
        //查询用户的所有博客
        List<blog> blogs = blogMapper.selectblogBymailbox(blog.getUser());
        blogdata blogdata = new blogdata();
        for (int i = 0; i < blogs.size(); i++) {
            blogdata.setBrowse(blogs.get(i).getBrowse() + blogdata.getBrowse());
            blogdata.setComment(blogs.get(i).getComment() + blogdata.getComment());
            blogdata.setFabulous(blogs.get(i).getFabulous() + blogdata.getFabulous());
            blogdata.setCollection(blogs.get(i).getCollection() + blogdata.getCollection());
        }
        attention a=new attention();
        a.setT(users.getMailbox());
        //假数据，粉丝数量
        blogdata.setFans(attentionMapper.selectFans(a).size());
        blogdata.setQriginal(blogs.size());
        blogdata.setGrade(users.getGrade());

        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        Date d2 = df.parse(users.getFirstlinecode());
        Date d1 = new Date();
        long diff = d1.getTime() - d2.getTime();//这样得到的差值是微秒级别
        long days = diff / (1000 * 60 * 60 * 24);

        blogdata.setCodeage(Double.parseDouble(String.format("%.1f", days * 1.0 / 365.0)));
        blogdata.setUsers(users);
        return blogdata.toString();
    }


    //查询博主的其他的博客
    @GetMapping("/selectother/{mailbox}")
    public String selectother(@PathVariable("mailbox") String mailbox) {
        List<userotherblog> list = new ArrayList<>();
        for (int i = 0; i < tagsMapper.selecttabs().size(); i++) {
            if (blogMapper.selectother(tagsMapper.selecttabs().get(i).getId(), mailbox).size() > 0) {
                tags t = new tags();
                t.setId(tagsMapper.selecttabs().get(i).getId());
                t.setName(tagsMapper.selecttabs().get(i).getName());
                userotherblog userotherblog = new userotherblog();
                userotherblog.setTags(t);
                userotherblog.setBlogList(blogMapper.selectother(tagsMapper.selecttabs().get(i).getId(), mailbox));
                list.add(userotherblog);
            }
        }
        return list.toString();
    }

    //增加博客
    @ResponseBody
    @RequestMapping(value = "/insertblog", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public JSONObject insertblog(@RequestBody JSONObject jsonParam) throws IOException {
        //获取系统时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        JSONObject result = jsonParam;
        blog blog = new blog();
        blog.setUser(jsonParam.get("mailbox").toString());
        blog.setBrowse(0);
        blog.setCollection(0);
        blog.setComment(0);
        blog.setFabulous(0);
        blog.setTime(dateFormat.format(date));
        blog.setTitle(jsonParam.get("title").toString());
        blog.setType(jsonParam.get("type").toString());
        List<blog> blogs = blogMapper.selectAllblog();
        String path=null;
        if (blogMapper.selectblogByid(1)==null){
             path = "C:\\manongyizhanFile\\users\\"+jsonParam.get("mailbox").toString()+"\\blog\\" + (1) + ".txt";
        }else {
             path = "C:\\manongyizhanFile\\users\\"+jsonParam.get("mailbox").toString()+"\\blog\\" + (blogs.get(0).getId() + 1) + ".txt";
        }
        File file = new File(path);
        //获取父目录
        File fileParent = file.getParentFile();
        //判断是否存在
        if (!fileParent.exists()) {
            //创建父目录文件
            fileParent.mkdirs();
        }
        file.createNewFile();
        write(path, jsonParam.get("blog").toString());
        blogMapper.insertblog(blog);
        //写一个博客添加10分
        Integral integral=new Integral();
        integral.setIntegral(10+integralMapper.selectinterfaceBymailbox(jsonParam.get("mailbox").toString()).getIntegral());
        integral.setMailbox(jsonParam.get("mailbox").toString());
        integralMapper.updateIntegral(integral);
        return jsonParam;
    }

    //把博客写道txt
    private void write(String path, String ss)
            throws IOException {
        //将写入转化为流的形式
        BufferedWriter bw = new BufferedWriter(new FileWriter(path));
        //一次写一行
        bw.write(ss);
        bw.newLine();  //换行用
        bw.close();
    }

    //返回博客txt
    @GetMapping("/selectblogtxt/{id}")
    public String selectblogtxt(@PathVariable("id") int id) {
        blog blog = blogMapper.selectblogByid(id);
        String path = "C:\\manongyizhanFile\\users\\" + blog.getUser() + "\\blog\\" + blog.getId() + ".txt";
        File filetxt = new File(path);
        StringBuilder result = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(filetxt));//构造一个BufferedReader类来读取文件
            String s = null;
            while ((s = br.readLine()) != null) {//使用readLine方法，一次读一行
                result.append(System.lineSeparator() + s);
            }
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }


    //根据id查询blog
    @GetMapping("/selectblog/{id}")
    public String selectblog(@PathVariable("id") int id) {

        return blogMapper.selectblog(id).toString();
    }

    //blog点赞
    @GetMapping("/fabulous/{id}")
    public String fabulous(@PathVariable("id") int id) {
        blog blog = blogMapper.selectblog(id);
        blogMapper.fabulous(id, blog.getFabulous() + 1);
        return "ok";
    }

    //blog点赞取消
    @GetMapping("/fabulouscancel/{id}")
    public String fabulouscancel(@PathVariable("id") int id) {
        blog blog = blogMapper.selectblog(id);
        blogMapper.fabulous(id, blog.getFabulous() - 1);
        return "ok";
    }

    //blog收藏
    @GetMapping("/collection/{id}")
    public String collection(@PathVariable("id") int id) {
        blog blog = blogMapper.selectblog(id);
        blogMapper.collection(id, blog.getCollection() + 1);
        return "ok";
    }

    //blog收藏取消
    @GetMapping("/collectioncancel/{id}")
    public String collectioncancel(@PathVariable("id") int id) {
        blog blog = blogMapper.selectblog(id);
        blogMapper.collection(id, blog.getCollection() - 1);
        return "ok";
    }

    //浏览增加
    @GetMapping("/browse/{id}")
    public String browse(@PathVariable("id") int id) {
        blog blog = blogMapper.selectblog(id);
        blogMapper.browse(id, blog.getBrowse() + 1);
        return "ok";
    }

    //根据邮箱查询博客
    @GetMapping("/selectblogBymailbox/{mailbox}")
    public String selectblogBymailbox(@PathVariable String mailbox) {
        return blogMapper.selectblogBymailbox(mailbox).toString();
    }

    //删除blog根据id
    @GetMapping("/deleteblogbyid/{id}")
    public void deleteblogbyid(@PathVariable int id) {
        blogMapper.deleteblogbyid(id);
    }

    //文章管理筛选栏
    @GetMapping("/filterblogdata")
    public String filterblogdata() {
        filter filter = new filter();
        int[] m = new int[12];
        for (int i = 0; i < m.length; i++) {
            m[i] = i + 1;
        }
        //获取系统时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
        int a = Integer.parseInt(dateFormat.format(date));
        int y[] = new int[a - 2017];
        for (int i = 0; i < y.length; i++) {
            y[i] = a - i;
        }
        filter.setMonth(m);
        filter.setYear(y);
        filter.setTags(tagsMapper.selecttabs());
        return filter.toString();
    }
}
